package cn.virens.common.easyexcel.dict;

import cn.virens.common.util.exception.APIException;
import org.dromara.hutool.core.collection.CollUtil;
import org.dromara.hutool.core.reflect.ConstructorUtil;

import java.util.Collection;
import java.util.List;
import java.util.function.Function;

public class ExcelDictBuilder<T> {
    private Function<T, Object> valueFun;
    private Function<T, String> keyFun;

    private final ExcelDict dict;

    public ExcelDictBuilder(List<String> headName) {
        this.dict = new ExcelDict(headName);
    }

    /**
     * 设置字典VALUE(导入内容)
     */
    public void setValueFun(Function<T, Object> valueFun) {
        this.valueFun = valueFun;
    }

    /**
     * 设置字典KEY(导出内容)
     */
    public void setKeyFun(Function<T, String> keyFun) {
        this.keyFun = keyFun;
    }

    public void setClazz(Class<? extends AbstractExcelDictConverter<?>> clazz) {
        this.dict.setConverter(ConstructorUtil.newInstance(clazz));
    }

    /**
     * 构建字典并存入
     */
    public ExcelDict build(Collection<T> list) throws APIException {
        CollUtil.forEach(list, (index, item) -> {
            Object value = valueFun.apply(item);
            String key = keyFun.apply(item);

            dict.put(key, value);
        });

        return dict;
    }

    /**
     * 构建字典并存入
     */
    public ExcelDict build(T[] array) throws APIException {
        for (int idx = 0; idx < array.length; idx++) {
            Object value = valueFun.apply(array[idx]);
            String key = keyFun.apply(array[idx]);

            dict.put(key, value);
        }

        return dict;
    }

}
